package controllers

import (
	"gitee.com/igolang/imoney/internal/app/system/services"
	"gitee.com/igolang/imoney/internal/common/httpResp"
	"gitee.com/igolang/imoney/internal/models/dao"
	"gitee.com/igolang/pkg/xgorm"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

var Notice = &notice{}

type notice struct{}

func (c *notice) List(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	data, err := services.Notice.List(ctx)
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	r.Data = data
}

func (c *notice) Detail(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	id := cast.ToInt64(ctx.Param("id"))
	row, err := dao.SysNotice.Where(dao.SysNotice.NoticeID.Eq(id)).Take()
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	// 解码
	data := xgorm.ModelToMapWithTag(row, "json")
	data["noticeContent"] = string(row.NoticeContent)
	r.Data = data
}

func (c *notice) Save(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	if err := services.Notice.Save(ctx); err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
}

func (c *notice) Delete(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	if err := services.Notice.Delete(ctx); err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
}
